package com.my.util;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.beust.jcommander.internal.Maps;

import freemarker.template.Configuration;
import freemarker.template.Template;
public class FreemarkUtils
{
	
  private static final String TEMPLATE_DIR = "template";
  private static final String CONTENT_ENCODING = "UTF-8";
  private static final Logger log =  LoggerFactory.getLogger(FreemarkUtils.class);
  private static Configuration configuration;

  static{
	  init(TEMPLATE_DIR);
  }
  
  public static void init(String templateDir){
	  try{
	      URL templateBasePath = FreemarkUtils.class.getClassLoader().getResource(templateDir);
	      configuration = new Configuration(Configuration.VERSION_2_3_22);
		  configuration.setDirectoryForTemplateLoading(new File(templateBasePath.toURI()));
	  } catch (Exception e) {
	      log.error("",e);
	  }
  }
  
  public static String getValueByTemplate(Map<String, Object> data,String templateName){
	  try {
		Template template = configuration.getTemplate(templateName);
		ByteArrayOutputStream bs = new ByteArrayOutputStream(1024);
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(bs, CONTENT_ENCODING));
		template.process(data, writer);
		writer.flush();
	    writer.close();
	    return  IOUtils.toString(bs.toByteArray(),CONTENT_ENCODING);
	} catch (Exception e) {
		e.printStackTrace();
	}
	  return null;
  }
  
  public static void main(String[] args) {
	  System.out.println(getValueByTemplate(Maps.<String, Object>newHashMap(), "reg_mail.ftl"));
  }

}